package com.ops.service.ns.system.beans;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;

import com.ops.schema.ns.system.OPSLookUps;
import com.ops.schema.ns.system.OPSRecordAuditInfo;
import com.ops.schema.ns.system.OPSRoles;
import com.ops.schema.ns.system.OPSUser;
import com.ops.schema.ns.system.RetrieveRolesRequest;
import com.ops.schema.ns.system.RetrieveRolesResponse;
import com.ops.schema.ns.system.SearchLookUpsRequest;
import com.ops.schema.ns.system.SearchLookUpsResponse;
import com.ops.schema.ns.system.SearchUsersRequest;
import com.ops.schema.ns.system.SearchUsersResponse;
import com.ops.schema.ns.system.UpdateUsersRequest;
import com.ops.schema.ns.system.UpdateUsersResponse;
import com.ops.service.ns.system.client.OnlinePayrollSystemServiceClient;
import com.ops.service.ns.system.exception.ServiceException;

public class UserMBean {

	private String name;
	private String type;
	private String status;
	private String mode;
	private String roleMode;
	private String delflag;
	private String saveStatus;
	private List<SelectItem> opsRoleList;
	private List<SelectItem> statusList;
	private List<OPSUser> opsuserlst;
	private OPSUser opsuser;
	private OPSRoles opsRole;
	private Map<String, OPSUser> opsuserMap;

	public void searchUsers() {
		System.out.println("Inside searchRules");
		SearchUsersRequest usersRequest = new SearchUsersRequest();
		usersRequest.setName(name);
		usersRequest.setStatus(status);
		OPSRecordAuditInfo uditInfo = new OPSRecordAuditInfo();
		uditInfo.setUpdatedBy(getuserId());
		uditInfo.setUpdatedSession(getSessionId());
		uditInfo.setAction("S");
		uditInfo.setObjectType(getMenuId());
		usersRequest.setOPSRecordAuditInfo(uditInfo);
		try {
			SearchUsersResponse usersResponse = OnlinePayrollSystemServiceClient
					.searchUsers(usersRequest);
			setOpsuserlst(usersResponse.getOPSUser());

		} catch (ServiceException e) {
			e.printStackTrace();
		}

	}

	public void resetUsers() {
		setName(null);
		setStatus(null);
		setType(null);
	}

	public void saveUsers(ActionEvent event) {

		UpdateUsersRequest updateRequest = new UpdateUsersRequest();
		OPSUser opsUsers = new OPSUser();
		opsUsers.setId(opsuser.getId());
		opsUsers.setName(opsuser.getName());
		opsUsers.setStatus(opsuser.getStatus());
		opsUsers.setPassword(opsuser.getPassword());
		if (opsuser.getOPSRoles() != null) {
			if (opsuser.getOPSRoles().size() > 0) {
				for (OPSRoles roles : opsuser.getOPSRoles()) {
					if (roles.getId() != null
							&& !roles.getId().equalsIgnoreCase("")) {
						roles.setOperationFlag("U");
						OPSRecordAuditInfo uditInfo = new OPSRecordAuditInfo();
						uditInfo.setUpdatedBy(getuserId());
						uditInfo.setUpdatedSession(getSessionId());
						uditInfo.setAction("U");
						uditInfo.setObjectType(getMenuId());
						roles.setOPSRecordAuditInfo(uditInfo);
						opsUsers.getOPSRoles().add(roles);
					}
				}
			}
		}

		opsUsers.setOperationFlag("U");
		OPSRecordAuditInfo uditInfo = new OPSRecordAuditInfo();
		uditInfo.setUpdatedBy(getuserId());
		uditInfo.setUpdatedSession(getSessionId());
		if (opsUsers.getId() != null)
			uditInfo.setAction("U");
		else
			uditInfo.setAction("I");
		uditInfo.setObjectType(getMenuId());
		opsUsers.setOPSRecordAuditInfo(uditInfo);
		updateRequest.getOPSUser().add(opsUsers);
		try {
			UpdateUsersResponse response = persistData(updateRequest);
			System.out.println("STATUS:"
					+ response.getServiceResult().getStatusMsg() + "Code:"
					+ response.getServiceResult().getStatusCode());
			setSaveStatus(response.getServiceResult().getStatusMsg());
			searchUsers();
		} catch (ServiceException e) {
			e.printStackTrace();
		}

	}

	public void delUsers(ActionEvent event) {
		if (mode != null && !mode.equalsIgnoreCase("")) {
			if (mode.startsWith("Del_") && delflag != null
					&& delflag.equalsIgnoreCase("Yes")) {
				setDelflag(null);
				UpdateUsersRequest updateRequest = new UpdateUsersRequest();
				String key = mode.replace("Del_", "").trim();
				OPSUser user = new OPSUser();
				user.setId(key);
				user.setOperationFlag("D");
				OPSRecordAuditInfo uditInfo = new OPSRecordAuditInfo();
				uditInfo.setUpdatedBy(getuserId());
				uditInfo.setUpdatedSession(getSessionId());
				uditInfo.setAction("D");
				uditInfo.setObjectType(getMenuId());
				user.setOPSRecordAuditInfo(uditInfo);
				updateRequest.getOPSUser().add(user);
				try {
					persistData(updateRequest);
					searchUsers();
				} catch (ServiceException e) {
					e.printStackTrace();
				}

			}
		}

	}

	public OPSUser addUsers() {
		setSaveStatus(null);
		if (mode != null && !mode.equalsIgnoreCase("")) {
			if (getOpsuserlst() != null) {
				opsuserMap = new HashMap<String, OPSUser>();
				for (OPSUser user : getOpsuserlst()) {
					System.out.println("Inside" + user.getId());
					opsuserMap.put(user.getId(), user);
				}
			}
			if (mode.equalsIgnoreCase("newAdd")) {
				opsuser = new OPSUser();
			} else if (mode.startsWith("Edit_")) {
				String key = mode.replace("Edit_", "").trim();
				System.out.println("Key:" + key);
				opsuser = opsuserMap.get(key);
			}
		}
		System.out.println("Inside addUsers:::" + mode);
		return opsuser;
	}

	public OPSRoles addUserRoles() {
		System.out.println("Inside Add User Role");
		opsRole = new OPSRoles();
		if (mode != null && !mode.equalsIgnoreCase("")) {
			if (mode.startsWith("EditAddRole_")) {
				String key = mode.replace("EditAddRole_", "").trim();
				System.out.println("Key::" + key);
				if (key != null && !key.equalsIgnoreCase("")) {
					System.out.println("Key:" + key);
					opsuser = opsuserMap.get(key);
					System.out.println("OPSRole:"
							+ opsuser.getOPSRoles().size());
					Map<String, OPSRoles> map = new HashMap<String, OPSRoles>();
					for (OPSRoles roles : opsuser.getOPSRoles()) {
						map.put(roles.getId(), roles);
					}
					if (roleMode != null && !roleMode.equalsIgnoreCase("")) {
						if (roleMode.equalsIgnoreCase("AddRole")) {
							opsRole = new OPSRoles();
						} else if (roleMode.startsWith("EditRole_")) {
							String roleId = roleMode.replace("EditRole_", "")
									.trim();
							System.out.println("roleId" + roleId);
							if (roleId != null && !roleId.equalsIgnoreCase("")) {
								opsRole = map.get(roleId);
							} else {
								opsRole = new OPSRoles();
							}
						}
					}
				} else {
					opsRole = new OPSRoles();
				}
			}
		}
		return opsRole;
	}

	public OPSUser saveUserRoles() {
		System.out.println("Inside saveUserRoles");
		if (mode != null && !mode.equalsIgnoreCase("")) {
			if (mode.startsWith("SaveUserRole_")) {
				String key = mode.replace("SaveUserRole_", "").trim();
				if (key != null && !key.equalsIgnoreCase("")) {
					System.out.println("Key:" + key);
					opsuser = opsuserMap.get(key);
					System.out.println("userName::"+opsuser.getName()+":::roleId::"+roleMode);
					if (roleMode != null && !roleMode.equalsIgnoreCase("")) {
						if (roleMode.startsWith("SaveRoleId_")) {
							String roleId = roleMode.replace("SaveRoleId_", "")
									.trim();
							System.out.println("Role Id:::"+roleId);
							if (roleId != null && !roleId.equalsIgnoreCase("")) {
								List<OPSRoles> temp = new ArrayList<OPSRoles>();
								int count = 0;
								for (OPSRoles roles : opsuser.getOPSRoles()) {
									if (roles.getId().equalsIgnoreCase(roleId)) {
										temp.add(opsRole);
									} else {
										count++;
										temp.add(roles);
									}
								}
								System.out.println("Count"+count);
								if(count != opsuser.getOPSRoles().size())
								{
								opsuser.getOPSRoles().clear();
								opsuser.getOPSRoles().addAll(temp);
								}else
								{
									opsuser.getOPSRoles().add(opsRole);
								}
								
							} 
						}
					}
				} else {
					opsuser.getOPSRoles().add(opsRole);

				}
			}
		}
		return opsuser;
	}

	public void delUserRoles(ActionEvent event) {

	}

	public UpdateUsersResponse persistData(UpdateUsersRequest updateUsersRequest)
			throws ServiceException {
		UpdateUsersResponse usersResponse = OnlinePayrollSystemServiceClient
				.saveUsers(updateUsersRequest);
		return usersResponse;
	}

	private String getSessionId() {

		FacesContext fCtx = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) fCtx.getExternalContext()
				.getSession(false);
		return session.getId();
	}

	private String getuserId() {

		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();
		Map<String, Object> sessionMap = externalContext.getSessionMap();
		return sessionMap.get("UserId").toString();
	}

	private String getMenuId() {

		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();
		Map<String, Object> sessionMap = externalContext.getSessionMap();
		return sessionMap.get("MenuId").toString();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getMode() {
		return mode;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public String getDelflag() {
		return delflag;
	}

	public void setDelflag(String delflag) {
		this.delflag = delflag;
	}

	public String getSaveStatus() {
		return saveStatus;
	}

	public void setSaveStatus(String saveStatus) {
		this.saveStatus = saveStatus;
	}

	public List<SelectItem> getStatusList() {
		if (statusList == null) {
			statusList = new ArrayList<SelectItem>();
			SearchLookUpsRequest masterRequest = new SearchLookUpsRequest();
			OPSRecordAuditInfo uditInfo = new OPSRecordAuditInfo();
			masterRequest.setOPSRecordAuditInfo(uditInfo);
			masterRequest.setType("USER-STATUS");
			try {
				SearchLookUpsResponse masterResponse = OnlinePayrollSystemServiceClient
						.searchLookUp(masterRequest);
				for (OPSLookUps master : masterResponse.getOPSLookUps()) {
					SelectItem item = new SelectItem(master.getCode(),
							master.getName());
					statusList.add(item);
				}
				System.out.println("statusList:" + statusList.size());
			} catch (ServiceException e) {
				e.printStackTrace();
			}

		}
		return statusList;
	}

	public void setStatusList(List<SelectItem> statusList) {
		this.statusList = statusList;
	}

	public List<OPSUser> getOpsuserlst() {
		return opsuserlst;
	}

	public void setOpsuserlst(List<OPSUser> opsuserlst) {
		this.opsuserlst = opsuserlst;
	}

	public OPSUser getOpsuser() {
		return opsuser;
	}

	public void setOpsuser(OPSUser opsuser) {
		this.opsuser = opsuser;
	}

	public Map<String, OPSUser> getOpsuserMap() {
		return opsuserMap;
	}

	public void setOpsuserMap(Map<String, OPSUser> opsuserMap) {
		this.opsuserMap = opsuserMap;
	}

	public List<SelectItem> getOpsRoleList() {
		if (opsRoleList == null) {
			opsRoleList = new ArrayList<SelectItem>();
			SelectItem defitem = new SelectItem("", "--Select--");
			opsRoleList.add(defitem);
			RetrieveRolesRequest masterRequest = new RetrieveRolesRequest();
			OPSRecordAuditInfo uditInfo = new OPSRecordAuditInfo();
			masterRequest.setOPSRecordAuditInfo(uditInfo);
			try {
				RetrieveRolesResponse masterResponse = OnlinePayrollSystemServiceClient
						.getRoles(masterRequest);
				for (OPSRoles master : masterResponse.getOPSRoles()) {
					SelectItem item = new SelectItem(master.getId(),
							master.getName());
					opsRoleList.add(item);
				}
				System.out.println("opsRoleList:" + opsRoleList.size());
			} catch (ServiceException e) {
				e.printStackTrace();
			}

		}
		return opsRoleList;
	}

	public void setOpsRoleList(List<SelectItem> opsRoleList) {
		this.opsRoleList = opsRoleList;
	}

	public OPSRoles getOpsRole() {
		return opsRole;
	}

	public void setOpsRole(OPSRoles opsRole) {
		this.opsRole = opsRole;
	}

	public String getRoleMode() {
		return roleMode;
	}

	public void setRoleMode(String roleMode) {
		this.roleMode = roleMode;
	}

}
